package gui;

import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.AffineTransform;

public class RotateController {

	private Point centerPoint;
	private Point pressPoint;
	private boolean click = false;
	private boolean doubleClick = false;
	private AffineTransform transform;
	
	public RotateController() {
		centerPoint = new Point(377, 278);

		transform = new AffineTransform();
		transform.setToIdentity();
	}
	
	public void setCenterPoint(Point point) {
		centerPoint = point;
	}
	
	public void setPressPoint(Point point) {
		if(pressPoint != null && point.distance(pressPoint) < 3) {
			doubleClick = true;
		}
		pressPoint = point;
		click = true;
	}

	public void setDragPoint(Point point) {
		boolean moveNode = false;
		if(!click) {
			return;
		}
		
		int distance = (pressPoint.x - point.x) * (pressPoint.x - point.x)
					+ (pressPoint.y - point.y) * (pressPoint.y - point.y);
		moveNode = distance >= 9;
		
		if(moveNode) {
			click = false;
			doubleClick = false;
		}
	}
	
	public void setReleasePoint(Point point, Point eventPoint) {
		if(doubleClick) {
			transform.setToIdentity();
			centerPoint = eventPoint;
		}
		else if(click) {
			setCenterPoint(point);
		}
	}
	
	public boolean isClicked() {
		return click;
	}
	
	public void draw(Graphics2D g) {
		g.setColor(Paintbrush.seaFoam);
		g.setStroke(new BasicStroke(3));
		g.drawOval(centerPoint.x - 5, centerPoint.y - 5, 10, 10);
		g.setStroke(new BasicStroke(1));
		g.setColor(Paintbrush.navy);
	}

	public void createTransform(Point currentPoint) {
		transform.translate(centerPoint.x, centerPoint.y);
		
		double h1 = Math.sqrt((pressPoint.x - centerPoint.x) * (pressPoint.x - centerPoint.x)
				+ (pressPoint.y - centerPoint.y) * (pressPoint.y - centerPoint.y));
		double h2 = Math.sqrt((currentPoint.x - centerPoint.x) * (currentPoint.x - centerPoint.x)
				+ (currentPoint.y - centerPoint.y) * (currentPoint.y - centerPoint.y));
		double scaleFactor = h2 / h1;
		
		transform.rotate(Math.atan2(-1 * (pressPoint.y - centerPoint.y) / h1, (pressPoint.x - centerPoint.x) / h1));
		transform.scale(scaleFactor, scaleFactor);
		transform.rotate(Math.atan2((currentPoint.y - centerPoint.y) / h2, (currentPoint.x - centerPoint.x) / h2));
		
		transform.translate(-1 * centerPoint.x, -1 * centerPoint.y);
	}

	public AffineTransform getTransform() {
		return transform;
	}
}
